//
//  HPInfo.m
//  HPNetworking
//
//  Created by phq on 2022/3/19.
//  Copyright © 2022 pixy. All rights reserved.
//

#import "HPInfo.h"
#import "HPEncode.h"
#import "HPHelper.h"
#import "HPRequest.h"

static NSString * const k_token_secret_key = @"hprequestkit_token_secret_key";
static NSString * const k_access_token_key = @"hprequestkit_AccessToken";
static NSString * const k_secret_key = @"hprequestkit_Secret";
static NSString * const kDES_Php_Key = @"M*JOB@10";
static NSString * const kDES_Java_Key = @"7&beq<DQ.=U`lZmp";
@implementation HPInfo

- (void)infoForcedUpdate:(BOOL)update {
    if (update) {
        [self updateAccessToken];
    }else {
        NSDictionary *data = [self getTokenWithType:_type];
        self.accessToken = [data objectForKey:k_access_token_key];
        self.secret = [data objectForKey:k_secret_key];
        if (![_accessToken isKindOfClass:[NSString class]] || _accessToken == nil || [_accessToken length] == 0 || [_accessToken containsString:@"null"] || [_accessToken containsString:@"(null)"] || ![_secret isKindOfClass:[NSString class]] || _secret == nil || [_secret length] == 0 || [_secret containsString:@"null"] || [_secret containsString:@"(null)"]) {
            [self updateAccessToken];
            HPLog(@"-🚀🚀🚀🚀🚀🚀🚀🚀🚀--AccessToken或secret不存在--%@: ----%@---class:---%@----%@",self.accessToken,self.secret,self.accessToken.class,self.secret.class);
        }else{
            [self completeCallback:YES token:_type];
        }
    }
    
}

- (void)updateAccessToken {
    HPRequestModel *mo = [[HPRequestModel alloc] init];
    mo.dateGMT = [HPHelper stringFromDateGMT];
    mo.type = _type;
    // new system
    if (_type > 6) {
        mo.postParams = [NSString stringWithFormat:@"device_id=%@",[HPRequest getMacAddress]];
        mo.getParams = @"op=token&func=getTokenSecret";
    }else {
        // old system
        NSInteger ts = [NSDate timeIntervalSinceReferenceDate];
        NSDictionary *info = @{@"user":HPUserType(_type),@"pwd":HPPwdType(_type),@"time":@(ts).stringValue,@"vflag":@"1"};
        mo.postParams = [mo paramFormat:info];
        mo.getParams = @"op=init_log&func=getAccessToken";
        self.url = [NSString stringWithFormat:@"%@&%@",_url,mo.getParams];
    }
    __weak typeof(self) weakSelf = self;
    [HPNetworking postWithModel:mo succeed:^(id _Nullable result) {
        if (result == nil || ![result isKindOfClass:[NSDictionary class]]) {
            HPLog(@"---AccessToken--Error: fetchTokenSecret result is null");
            return ;
        }else HPLog(@"--AccessToken--succeed - %zd",mo.type);
        
        if (mo.type > 6) {
            weakSelf.secret = [HPHelper base64EncodedWithString:HPUserType(mo.type)];
            NSDictionary *data = [result valueForKey:@"data"];
            if (data && [data isKindOfClass:[NSDictionary class]]) {
                NSString *secret = [data valueForKey:@"secret"];
                if ([secret isKindOfClass:[NSString class]] && ![secret containsString:@"null"]) {
                    weakSelf.accessToken = secret;
                }
            }
        }else {
            weakSelf.secret = [result valueForKey:@"secret"];
            weakSelf.accessToken = [result valueForKey:@"access_token"];
        }
        if ((![weakSelf.secret isKindOfClass:[NSString class]] || weakSelf.secret == nil || [weakSelf.secret length] == 0 || [weakSelf.secret containsString:@"null"]) ||
            (![weakSelf.accessToken isKindOfClass:[NSString class]] || weakSelf.accessToken == nil || [weakSelf.accessToken length] == 0 || [weakSelf.accessToken containsString:@"null"] )) {
            return;
        }
        [weakSelf saveTokenWithType:mo.type secret:weakSelf.secret token:weakSelf.accessToken];
        [weakSelf completeCallback:YES token:weakSelf.type];
    } failure:^(NSString * _Nullable error) {
        HPLog(@"--AccessToken--failure - %zd",mo.type);
        [weakSelf completeCallback:NO token:mo.type];
    }];
}

// save token
- (void)saveTokenWithType:(ATokenType)type secret:(NSString *)secret token:(NSString *)token {
    HPLog(@"-🚀🚀🚀🚀🚀🚀🚀🚀🚀--AccessToken或secret保存成功- %zd - %@ --- %@",type,secret,token);
    NSString *key = [NSString stringWithFormat:@"%@_%@",k_token_secret_key,HPUserType(_type)];
    [[NSUserDefaults standardUserDefaults] setValue:@{k_secret_key:secret,k_access_token_key:token} forKey:key];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

// get token
- (NSDictionary *)getTokenWithType:(ATokenType)type {
    NSString *key = [NSString stringWithFormat:@"%@_%@",k_token_secret_key,HPUserType(_type)];
    return [[NSUserDefaults standardUserDefaults] objectForKey:key];
}

- (void)completeCallback:(BOOL)isSucceed token:(ATokenType)type {
    if (_complete != nil) {
        NSDictionary *data = [self getTokenWithType:type];
        self.accessToken = [data objectForKey:k_access_token_key];
        self.secret = [data objectForKey:k_secret_key];
        HPLog(@"-🚀🚀🚀🚀🚀🚀🚀🚀🚀--AccessToken和secret已存在--%@: ----%@",self.accessToken,self.secret);
        self.complete(isSucceed,type);
        self.complete = nil;
    }
}

//DES加密,后base64,UTF8编码
- (NSString *)encodeFromString:(NSString *)str {
    NSString *value = nil;
    if (str.length > 0) {
        NSData *data = [HPHelper encryptDES:str withKey:[self desKey]];
        NSString *base64Str = [data base64Encode];
        value = [base64Str stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    }
    return value;
}

- (NSDictionary*)encodePostParams:(NSString*)pParams getParams:(NSString*)gParams {
    NSString *getParam = [self encodeFromString:gParams];
    NSString *postParam = [self encodeFromString:pParams];
    NSDictionary *dict;
    if (self.type > 6) {
        dict = @{@"g":getParam?:@"",
                 @"p":postParam?:@"",
                 @"encode":@"base64",
                 @"version":self.ver};
    }else {
        dict = @{@"g":getParam?:@"",
                 @"p":postParam?:@"",
                 @"encode":@"base64"};
    }
    
    NSMutableString *url = [[NSMutableString alloc] initWithString:_url];
    if ([url containsString:@"index.php"]) {
        NSRange urlRange=[url rangeOfString:@"index.php"];
        [url replaceCharactersInRange:urlRange withString:@"index_des.php"];
    }else if ([url containsString:@"indexp.php"]) {
        NSRange urlRange=[url rangeOfString:@"indexp.php"];
        [url replaceCharactersInRange:urlRange withString:@"index_des.php"];
    }
    NSDictionary *resultDic = @{@"path":[url copy],@"param":dict};
    return resultDic;
}

- (id)decodeObject:(id _Nullable )object model:(__kindof HPRequestModel *_Nonnull)model {
    NSString *receive = nil;
    if(object) {
        NSStringEncoding enc = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
        receive = [[NSString alloc] initWithData:object encoding:enc];
        object = [HPHelper dataWithBase64EncodedString:receive];
        object = [HPHelper decryptDES:object withKey:[self desKey]];
    }
    NSDictionary *dic = nil;
    NSError *error = nil;
    if (object != nil) {
        dic = [NSJSONSerialization JSONObjectWithData:object options:NSJSONReadingAllowFragments error:&error];
    }
    
    if (dic == nil) {
        NSString *code,*desc;
        if (receive == nil) {
            code = @"-1";
            desc = @"【HPNetwork提示】接收数据为空";
        }else if ([receive isEqualToString:@"ZTj27Nlds0F7Aqp3yh8l9su56rTyzZyM"]) {
            code = @"-5";
            desc = @"【HPNetwork提示】token失效";
        }else {
            code = @"-2";
            desc = @"【HPNetwork提示】JSON格式化失败";
        }
        dic = @{@"code":code,@"desc":desc,@"data":[HPHelper utf8Encode:receive]};
    }
    return dic;
}

- (NSString *)desKey {
    NSString *key;
    if (_type <= 6) {
        key = kDES_Php_Key;
    }else {
        key = kDES_Java_Key;
    }
    return key;
}

@end
